package com.lw.leetcode.arr.b;

/**
 * arr
 * 402. 移掉K位数字
 *
 * @Author liw
 * @Date 2021/5/13 10:55
 * @Version 1.0
 */
public class RemoveKdigits {

    public static void main(String[] args) {
        RemoveKdigits test = new RemoveKdigits();
        String s = test.removeKdigits("13402", 1);
        System.out.println(s);
    }

    public String removeKdigits(String num, int k) {
        int length = num.length();
        if (length == k) {
            return "0";
        }
        char[] chars = new char[length + 2];
        char[] arr = num.toCharArray();
        int index = 2;
        char item = arr[0];
        chars[0] = 48;
        chars[1] = item;
        int count = k;
        boolean flag = true;
        for (int i = 1; i < length; i++) {
            char c = arr[i];
            if (flag && c < item) {
                index--;
                i--;
                item = chars[index - 1];
                count--;
                if (count == 0) {
                    flag = false;
                }
            } else {
                chars[index++] = c;
                item = c;
            }
        }
        count = length - k;
        for (int i = 1; i <= count; i++) {
            if (chars[i] != 48) {
                return new String(chars, i, count - i + 1);
            }
        }
        return "0";
    }


}
